const schedule = require('node-schedule');
const axios = require('axios');
const config = require('./config')
const mysql = require('./mysqlPool')
const cheerio = require('cheerio');

const fs = require("fs");

async function run() {
    console.log(formatTime(new Date())+" DAQ START...")
    fs.readFile("master-status", 'utf-8', (err, data) => {
        if (err) throw err;
        //console.log(data)
        saveDs(data)
    });
   
}




async function saveDs(html){

    let server = {
        ServerName:'',

        baseStatsTable:{
            Start_time:'',
            Last_contact:'',
            Version:'',
            Requests_Per_Second:0,
            Num_Regions:0,
        },

        memoryStatsTable:{
            Used_Heap:0,
            Max_Heap:0,
            Memstore_Size:0,
        },

        requestStatsTable:{
            Request_Per_Second:0,
            Read_Request_Count:0,
            Filtered_Read_Request_Count:0,
            Write_Request_Count:0,
        },

        storeStatsTable:{
            Num_Stores:0,
            Num_Storefiles:0,
            Storefile_Size_Uncompressed:0,
            Storefile_Size:0,
            Index_Size:0,
            Bloom_Size:0,
        },
       
        compactionStatsTable:{
            Num_Compacting_Cells:0,
            Num_Compacted_Cells:0,
            Remaining_Cells:0,
            Compaction_Progress:0,
        },
        
    }

    let ss = [];

    //console.log(html)
    let $ = cheerio.load(html);
    
    let master = $(".page-header").text().trim();

    $("#baseStatsTable tbody").first().children("tr").each(function(){

         let t_server = {};
       
        t_server.ServerName = $(this).children().eq(0).text().trim();
        t_server.baseStatsTable = {
            Start_time: formatTime(new Date($(this).children().eq(1).text().trim())),
            Last_contact: $(this).children().eq(2).text().trim(),
            Version: $(this).children().eq(3).text().trim(),
            Requests_Per_Second: Number($(this).children().eq(4).text().trim()),
            Num_Regions: Number($(this).children().eq(5).text().trim()),
        };
        ss.push(t_server);
    })

    let index = 0;
    $("#memoryStatsTable tbody").first().children("tr").each(function(){
        ss[index].memoryStatsTable = {
            Used_Heap:formatStorageUnit($(this).children().eq(1).text().trim()),
            Max_Heap:formatStorageUnit($(this).children().eq(2).text().trim()),
            Memstore_Size:formatStorageUnit($(this).children().eq(3).text().trim()),
        };
        index++;
		
    })

    index = 0;
    $("#requestStatsTable tbody").first().children("tr").each(function(){
        ss[index].requestStatsTable = {
            Request_Per_Second: Number($(this).children().eq(1).text().trim()),
            Read_Request_Count: Number($(this).children().eq(2).text().trim().replace(/,/g,"")),
            Filtered_Read_Request_Count: Number($(this).children().eq(3).text().trim()),
            Write_Request_Count: Number($(this).children().eq(4).text().trim()),
        };
        index++;
			
    })

    index = 0;
    $("#storeStatsTable tbody").first().children("tr").each(function(){
        ss[index].storeStatsTable={
            Num_Stores: Number($(this).children().eq(1).text().trim()),
            Num_Storefiles: Number($(this).children().eq(2).text().trim()),
            Storefile_Size_Uncompressed: formatStorageUnit($(this).children().eq(3).text().trim()),
            Storefile_Size: formatStorageUnit($(this).children().eq(4).text().trim()),
            Index_Size: formatStorageUnit($(this).children().eq(5).text().trim()),
            Bloom_Size: formatStorageUnit($(this).children().eq(6).text().trim()),
        };
        index++;
		
    })

    index = 0;
    $("#compactionStatsTable tbody").first().children("tr").each(function(){
        ss[index].compactionStatsTable={
            Num_Compacting_Cells: Number($(this).children().eq(1).text().trim()),
            Num_Compacted_Cells: Number($(this).children().eq(2).text().trim()),
            Remaining_Cells: Number($(this).children().eq(3).text().trim()),
            Compaction_Progress: Number($(this).children().eq(4).text().trim().replace("%",'')),
        };
        index++;
    })

    console.log(ss)

   // console.log(master)

}


const formatNumber = n => {
    
    n = n.toString()
    return n[1] ? n : '0' + n
}


/**
 * 统一以KB为单位
 * input: 1 MB
 * output: 1024 (KB)
 */
const formatStorageUnit=d=>{
    if(d=='') return 0;
    
    let ds = d.split(' ');
    
    if(ds[0] == 0) return 0;

    switch (ds[1]){
        case 'B': return 0;
        case 'KB': return ds[0]*1;
        case 'MB': return ds[0]*1024;
        case 'GB': return ds[0]*1024*1024;
        case 'TB': return ds[0]*1024*1024*1024;
    }
    return 0
}

const formatTime = date => {
    date.setUTCDate(+8);
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
  
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  }

module.exports = {
    run,
}